using System;
using System.Collections;
using System.Text;

namespace bOS.XML
{
	public class XMLNode
	{
		string sName=string.Empty;
		string sValue = string.Empty;

		XMLAttributes vAttributes = new XMLAttributes();
		XMLNodes vNodes = new XMLNodes();

		static char[] vSpecialCharacter = {'&'};
		static String[] vSpecialCode = {"&amp;"};

		public XMLNode()
		{
		}

		public XMLNode(string _Name)
		{
			sName = _Name;
		}

		public XMLNode(string _Name, string _Value)
		{
			sName = _Name;
			sValue = _Value;
		}

		public XMLNode(string _Name, int _Value)
		{
			sName = _Name;
			sValue = _Value.ToString();
		}

		public XMLNode(string _Name, long _Value)
		{
			sName = _Name;
			sValue = _Value.ToString();
		}

		public void SetValue(string _Value)
		{
			sValue = _Value;
		}

		public void SetName(string _Value)
		{
			sName = _Value;
		}


		public int AddAttribute ( XMLAttribute attribute )
		{
			return vAttributes.Add (attribute);
		}

		public int AddNode ( XMLNode node)
		{
			return vNodes.Add ( node);
		}

		static public String getValueTranscoded(ref String sValue)
		{
			if ( sValue == null ) 
				return string.Empty;

			StringBuilder sbValue= new StringBuilder();
			bool bRet =true;
			for ( int i=0; i<sValue.Length; i++)
			{
				bRet = true;

				for ( int j=0; j<1 && bRet; j++) 
				{
					if ( sValue[i] == vSpecialCharacter[j]) 
					{
						sbValue.Append (vSpecialCode[j]);
						bRet=false;
					}
				}

				if ( bRet )
					sbValue.Append (sValue[i]);
			}

			return sbValue.ToString();
		}



		public string GetXML(bool bIndent , int iLevel)
		{
			StringBuilder sbXml = new StringBuilder();

			StringBuilder sbIdentator = new StringBuilder();
			string sSeparator = "\r\n";
			if ( bIndent )
			{
				for ( int i=0; i<iLevel; i++)
					sbIdentator.Append ('\t');
			}
			else
			{
				sSeparator = "";
			}

			sbXml.Append (sbIdentator.ToString());
			sbXml.Append ("<");
			sbXml.Append (sName);

			//Attributes
			sbXml.Append (vAttributes.GetXML());

			sbXml.Append (">");

			if ( vNodes.Count > 0 )
			{
				sbXml.Append (sSeparator);
			}

			sbXml.Append (XMLNode.getValueTranscoded (ref sValue));

			sbXml.Append (vNodes.GetXML(bIndent, iLevel+1));

			if ( vNodes.Count > 0 )
			{
				sbXml.Append (sbIdentator.ToString());
			}

			sbXml.Append ("</");
			sbXml.Append (sName);
			sbXml.Append (">");
			sbXml.Append (sSeparator);

			return sbXml.ToString();
		}
	}
}
